package com.vlong.town.controller.admin.role;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONArray;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.vlong.town.controller.base.BaseController;
import com.vlong.town.entity.base.DataMessage;
import com.vlong.town.entity.base.TreeData;
import com.vlong.town.entity.menu.Menu;
import com.vlong.town.entity.role.Role;
import com.vlong.town.entity.roleMenuRef.RoleMenuRef;
import com.vlong.town.service.menu.MenuService;
import com.vlong.town.service.role.RoleService;
import com.vlong.town.service.roleMenuRef.RoleMenuRefService;
import com.vlong.town.util.common.TownConstant;
import com.vlong.town.util.pagination.PageTag;

@Controller
@RequestMapping("/role")
public class RoleController extends BaseController{

	@Autowired
	private RoleService roleService;
	@Autowired
	private MenuService menuService;
	@Autowired
	private RoleMenuRefService  roleMenuRefService;
	
	 /**
     * 进入角色列表页面
     * @param pageNo 当前页码
     * @param pageSize 每页记录数
     * @return role/list_role
     */
    @RequestMapping("/list")
    public String gotoRoleListPage(
            @RequestParam(required=false, value="pageNo") Integer pageNo,
            @RequestParam(required=false, value="pageSize") Integer pageSize,
            @RequestParam(required=false, value="roleName") String roleName) {
        PageHelper.startPage(getPageNo(pageNo), getPageSize(pageSize));
        PageHelper.orderBy("update_time DESC");
        List<Role> queryList = roleService.queryList(null, null, 1, getOrgId(), 1, TownConstant.DEL_FLAG_0, null, roleName, null, null, null);
        PageInfo<Role> pageInfo = new PageInfo<Role>(queryList);
        PageTag<Role> pt = new PageTag<Role>(request, "list", pageInfo);
        request.setAttribute("pageHtml", pt.getPageHtml());
        request.setAttribute("roleName", roleName);
        request.setAttribute("roleList", queryList);
        return "admin/role/list_role";
    }

    /**
     * 跳转角色添加页面
     * @return
     */
    @RequestMapping("/addRole")
    public  String  addRole(){
    	// 查询系统菜单信息
		List<Menu> menuList = this.menuService.queryList(null, null, null, null, null, 0,
				null, null, null, null, null, null, null, null, null, null,
				null, null);
		List<TreeData> menuTreeDataList = new ArrayList<TreeData>();
		menuTreeDataList.add(new TreeData("0", null, "菜单权限[选择角色所拥有的菜单权限]", false, true));
		for (Menu menu : menuList) {
			menuTreeDataList.add(new TreeData(menu.getMenuId().toString(), menu.getMenuPid().toString(), menu.getMenuName() + "[" + (menu.getMenuDesc() == null || "".equals(menu.getMenuDesc().trim()) ? "—"  : menu.getMenuDesc()) + "]", false, true));
		}
		request.setAttribute("menuTreeData",JSONArray.toJSONString(menuTreeDataList));
    	return  "admin/role/add_role";
    }
    
    /**
     * 添加角色
     * @param roleName 角色名称
     * @param roleDesc 角色描述
     * @return DataMessage 消息实体
     */
    @ResponseBody
    @RequestMapping("/executeAddRole")
    public  DataMessage  executeAddRole(
    		@RequestParam(required=false, value="roleName") String roleName,
    		@RequestParam(required=false, value="roleDesc") String roleDesc,
    		@RequestParam(required=false, value="menuIds") String menuIds
    		){
    	DataMessage dm=new DataMessage();
    	if(!this.validateStringProperty(roleName, 1, 50)) {
            dm.setResult(TownConstant.RESULT_CODE_PARAMETER_ERROR);
            dm.setMessage("角色名称不合法");
        } else if(!this.validateStringProperty(menuIds, 1, 128)){
        	dm.setResult(TownConstant.RESULT_CODE_PARAMETER_ERROR);
            dm.setMessage("菜单不合法");
        }else{
        	this.roleService.add(null, null, 1, getOrgId(), 1, TownConstant.DEL_FLAG_0, null, roleName, roleDesc, System.currentTimeMillis(), null,menuIds);
        	dm.setResult(TownConstant.RESULT_CODE_SUCCESS);
            dm.setMessage("用户添加成功");
        }
    	return  dm;
    }
    
    /**
     * 查询角色对象
     * @param roleId
     * @return String
     */
    @RequestMapping("/editRole/{roleId}")
    public  String  editRole(
    		@PathVariable(required=false, value="roleId") Long roleId
    		){
    	// 查询菜单信息
		List<Menu> menuList = this.menuService.queryList(null, null, null, null, null, 0,
				null, null, null, null, null, null, null, null, null, null,
				null, null);
		List<RoleMenuRef> menuRefList = this.roleMenuRefService.queryListByRoleId(roleId);
		List<TreeData> menuTreeDataList = new ArrayList<TreeData>();
		menuTreeDataList.add(new TreeData("0", null, "菜单权限[选择角色所拥有的菜单权限]", false, true));
		for (Menu menu : menuList) {
			boolean isChecked = false;
			for(RoleMenuRef ref : menuRefList) {
				if(menu.getMenuId().longValue() == ref.getMenuId().longValue()) {
					isChecked = true;
					break;
				}
			}
			menuTreeDataList.add(new TreeData(menu.getMenuId().toString(), menu.getMenuPid().toString(),
					menu.getMenuName() + "[" + (menu.getMenuDesc() == null || "".equals(menu.getMenuDesc().trim())
							? "—" : menu.getMenuDesc()) + "]",
					isChecked, true));
		}
    	
    	Role role = this.roleService.queryById(roleId);
    	request.setAttribute("menuTreeData",JSONArray.toJSONString(menuTreeDataList));
    	request.setAttribute("role", role);
    	return  "admin/role/edit_role";
    }
    
    /**
     * 修改角色
     * @param roleName  角色名称
     * @param roleDesc  角色描述
     * @param roleId  角色Id 
     * @return DataMessage 消息实体
     */
    @ResponseBody
    @RequestMapping("/executeEditRole")
    public  DataMessage  executeEditRole(
    		@RequestParam(required=false, value="roleId") Long roleId,
    		@RequestParam(required=false, value="roleName") String roleName,
    		@RequestParam(required=false, value="roleDesc") String roleDesc,
    		@RequestParam(required=false, value="menuIds") String menuIds
    		){
    	DataMessage dm=new DataMessage();
    	if(!this.validateStringProperty(roleName, 1, 50)) {
            dm.setResult(TownConstant.RESULT_CODE_PARAMETER_ERROR);
            dm.setMessage("角色名称不合法");
            return dm;
        }else{
        	this.roleService.edit(roleId, null, null, getOrgId(), null, null, null, roleName, roleDesc, null, System.currentTimeMillis(),menuIds);
        	dm.setResult(TownConstant.RESULT_CODE_SUCCESS);
            dm.setMessage("用户修改成功");
        }
    	return  dm;
    }
    
    /**
     * 删除角色
     * @param roleId 角色id
     * @return DataMessage
     */
    @ResponseBody
    @RequestMapping("/delete")
    public  DataMessage  delete(@RequestParam(required=false, value="roleId") Long roleId){
    	DataMessage dm = new DataMessage();
        if(roleId != null && roleId > 0L) {
        	this.roleService.edit(roleId, null, null, null, null, TownConstant.DEL_FLAG_1, null, null, null, null, null,null);
            dm.setResult(TownConstant.RESULT_CODE_SUCCESS);
            dm.setMessage("角色删除成功");
        } else {
            dm.setResult(TownConstant.RESULT_CODE_PARAMETER_ERROR);
            dm.setMessage("参数错误");
        }
        return dm;
    }
    
    /**
     * 批量删除角色
     * @param roleIds
     * @return DataMessage
     */
    @ResponseBody
    @PostMapping("/batchDelete")
    public DataMessage batchDeleteUser(@RequestParam(required=true, value="roleIds") String roleIds) {
        DataMessage dm = new DataMessage();
        if(this.validateStringProperty(roleIds, 1, 128)) {
            String[] roleIdArray = roleIds.split(",");
            for(String roleId : roleIdArray) {
            	this.roleService.edit(Long.parseLong(roleId), null, null, null, null, TownConstant.DEL_FLAG_1, null, null, null, null, null,null);
            }
            dm.setResult(TownConstant.RESULT_CODE_SUCCESS);
            dm.setMessage("角色删除成功");
        } else {
            dm.setResult(TownConstant.RESULT_CODE_PARAMETER_ERROR);
            dm.setMessage("参数错误");
        }
        return dm;
    }
    
    
    
    
	
}
